package com.gxa.luckin.admin.service.impl;

import com.gxa.luckin.admin.repository.AdminRepository;
import com.gxa.luckin.admin.service.AdminService;
import com.gxa.luckin.core.exception.BusinessException;
import com.gxa.luckin.core.exception.MessageCode;
import com.gxa.luckin.core.pojo.Admin;
import com.gxa.luckin.core.service.impl.BaseServiceImpl;
import com.gxa.luckin.core.utils.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("adminService")
@Transactional(rollbackFor = Throwable.class)
public class AdminServiceImpl implements AdminService {
    @Resource
    AdminRepository adminRepository;
    @Override
    public Admin login(String username, String password) {
        Admin admin = adminRepository.findByNameAndPassword(username,MD5Util.encode(password));

        return admin;
    }
    @Override
    public Admin register(String username, String password) throws BusinessException{
        Admin admin=new Admin();
        Admin byName = adminRepository.findByName(username);
        if(byName==null) {
            admin.setName(username);
            admin.setPassword(MD5Util.encode(password));
            Admin save = adminRepository.save(admin);
            return save;
        }else {
            throw new BusinessException(MessageCode.ADMIN_REGISTER_ERROR);
        }
    }
}
